$(document).ready(function(){
  
  //alert("21");
  //temporary fix for removing  All at filter 
  $(".filters span[key='all']").parent('li').remove();

  $("select").select2();
  //console.log(navigator);
  // Hide All in initial
  jQuery("select.brandsorter option:contains('All')").attr("disabled", "disabled");
 
  //. . . . .  Filter toggle
  /* added by ian for reset */
 $(".gallery-filter .filters a[href='#currentfilter']").click(function() {
    $(this).children("span").toggleClass("expand");
    $("#currentfilter").slideToggle("slow");
    return false;
  });
 //alert();

  jQuery("#reset-price").click(function(e) {
    orderDevices(e,jQuery("ul#price li a").first());
    updatePageIndicator(); 
    jQuery("#current-filter-price-container").hide();
    hideReset();
    jQuery("#label-price, #price").show();
    //jQuery("#label-current-filter, #currentfilter, #current-filter-price-container").hide();
  });
  
  jQuery("#reset-brand").click(function(e) {
    orderDevices(e,jQuery("ul#price li a").first());
    jQuery(".brand .select2-chosen").text("All");
    orderDevices(e,jQuery("div.sorter select"));
    updatePageIndicator(); 
    jQuery("#current-filter-brand-container").hide();
    hideReset();
    sortGallery();

    //jQuery("#label-current-filter, #currentfilter, #current-filter-price-container").hide();
  }); 
  
  
      $(".gallery-filter a[href='#filter']").click(function(){
            //console.log("Click .gallery-filter a[href='#filter']");
            //console.log("Click #gallery-filter-by-collapse");
            $(this).children("span").toggleClass("expand");
            $(".gallery-filter .filters").slideToggle("slow");
            return  false;
        });
    
        $(".gallery-filter .filters a[href='#price']").click(function(){
            //console.log("Click .gallery-filter .filters a[href='#price']");
            $(this).children("span").toggleClass("expand");
            // I want jquery handle the toggle
            $("#price").slideToggle("slow");
            return false;
        });

        //
        $("#phoneGallery .wizard").css("margin-top","60px");
  // . . . . . . . . css fixes for gallery header
  $("#phoneGallery .breadcrumbs , .breadcrumbs").attr("style","top:0; position:absolute;");


  //fix for pageination toolbar
  $(".gallery-pagination").css("margin-left","0px");
   //fix for pageination toolbar
  $("#price a").css("text-decoration","underline");
  addHeader();  //this is gallery header
  

  var current_pos = getCookie("current_pos");
  if (current_pos > 1){
      //alert(current_pos + "TRUE");
      if(current_pos=="2") {
          // update selected device
          markSelectedDevice();

          jQuery("div.wizard a:nth-of-type(1)").attr("class","current done");
          jQuery("div.wizard a:nth-of-type(2)").attr("class","current");
          jQuery("div.wizard a:nth-of-type(3), div.wizard a:nth-of-type(4), div.wizard a:nth-of-type(5)").removeAttr("href");
      
          jQuery('.marg20Left').css("position","absolute");
          jQuery('.marg20Left').css("margin-top","0px");
          jQuery('.deviceInfosIns').css("margin-top","-70px","important");
          jQuery('.deviceInfosIns').css("margin-left","4px","important");
          jQuery('.gallery-filter').css("width","210px");
          jQuery('.deviceInfosIns').css("width","210px");
          jQuery(".deviceInfos").addClass("hidden");
          jQuery(".deviceInfosIns").addClass("block2");
          
          var mode = getCookie("mode");
          var gadget = getCookie("gadget");
          var price = getCookie("price");
          
          if(mode!="edit"){      
                 jQuery(".promoBox, .commitmentBox, .prepaidBox, .profileBox, .storeBox").removeClass("active");
                 jQuery('#pname, #pemail, #pdob, #padd').hide();
                 jQuery('#promo, #commitmentBox, #mobtel, #globestore').text("None");
                 jQuery('#gadget').text(gadget + " - " + price);
          }
    }
    if(current_pos=="3") {
          // update selected device
          markSelectedDevice();

          jQuery("div.wizard a:nth-of-type(1), div.wizard a:nth-of-type(2)").attr("class","current done");
          jQuery("div.wizard a:nth-of-type(3)").attr("class","current");
          jQuery("div.wizard a:nth-of-type(4), div.wizard a:nth-of-type(5)").removeAttr("href");
      
          jQuery('.marg20Left').css("position","absolute");
          jQuery('.marg20Left').css("margin-top","0px");
          jQuery('.deviceInfosIns').css("margin-top","-70px","important");
          jQuery('.deviceInfosIns').css("margin-left","9px","important");
          jQuery('.gallery-filter').css("width","210px");
          jQuery('.deviceInfosIns').css("width","210px");
          jQuery(".deviceInfos").addClass("hidden");
          jQuery(".deviceInfosIns").addClass("block2");

          var mode = getCookie("mode");
          var gadget = getCookie("gadget");
          var price = getCookie("price");
          var promo = getCookieR("promo");
          var commitmentBox = getCookieR("commitmentBox");
      
          if(mode!="edit"){      
              jQuery(".prepaidBox, .profileBox, .storeBox").removeClass("active");
              jQuery('#pname, #pemail, #pdob, #padd').hide();
              jQuery('#mobtel, #globestore').text("None");
              jQuery('#gadget').text(gadget + " - " + price);
              jQuery('#promo').html(promo);
              jQuery('#commitmentBox').text(commitmentBox);
          }
      }
      if(current_pos=="4") {
          jQuery("div.wizard a:nth-of-type(1), div.wizard a:nth-of-type(2),div.wizard a:nth-of-type(3)").attr("class","current done");
          jQuery("div.wizard a:nth-of-type(4)").attr("class","current");
          jQuery("div.wizard a:nth-of-type(5)").removeAttr("href");
      
          jQuery('.marg20Left').css("position","absolute");
          jQuery('.marg20Left').css("margin-top","0px");
          jQuery('.deviceInfosIns').css("margin-top","-70px","important");
          jQuery('.deviceInfosIns').css("margin-left","9px","important");
          jQuery('.gallery-filter').css("width","210px");
          jQuery('.deviceInfosIns').css("width","210px");
          jQuery(".deviceInfos").addClass("hidden");
          jQuery(".deviceInfosIns").addClass("block2");

          var mode = getCookie("mode");
          var gadget = getCookie("gadget");
          var price = getCookie("price");
          var promo = getCookieR("promo");
          var commitmentBox = getCookieR("commitmentBox");
          var mobtel = getCookieR("mobtel");
          
          if(mode!="edit"){      
            jQuery(".profileBox, .storeBox").removeClass("active");
            jQuery('#pname, #pemail, #pdob, #padd').hide();
            jQuery('#globestore').text("None");
            jQuery('#gadget').text(gadget + " - " + price);
            jQuery('#promo').html(promo);
            jQuery('#commitmentBox').text(commitmentBox);
            if(mobtel=="0"){jQuery('#mobtel').text("none");} else {jQuery('#mobtel').text(mobtel);}
          }
      }
      if(current_pos=="5") {
          jQuery("div.wizard a:nth-of-type(1),div.wizard a:nth-of-type(2),div.wizard a:nth-of-type(3),div.wizard a:nth-of-type(4)").attr("class","current done");
          jQuery("div.wizard a:nth-of-type(5)").attr("class","width100 current");
        
          jQuery('.marg20Left').css("position","absolute");
          jQuery('.marg20Left').css("margin-top","0px");
          jQuery('.deviceInfosIns').css("margin-top","-70px","important");
          jQuery('.deviceInfosIns').css("margin-left","9px","important");
          jQuery('.gallery-filter').css("width","210px");
          jQuery('.deviceInfosIns').css("width","210px");
          jQuery(".deviceInfos").addClass("hidden");
          jQuery(".deviceInfosIns").addClass("block2");

          var mode = getCookie("mode");
          var gadget = getCookie("gadget");
          var price = getCookie("price");
          var promo = getCookieR("promo");
          var commitmentBox = getCookieR("commitmentBox");
          var mobtel = getCookieR("mobtel");
          var username = getCookieR("username");
          var eadd = getCookieR("eadd");
          var bday = getCookieR("bday");
          var address = getCookieR("address");
          jQuery("p.pnone").hide();
          if(mode!="edit"){      
            jQuery(".storeBox").removeClass("active");
            jQuery("p.pnone").hide();
            jQuery('#globestore').text("None");
            jQuery('#gadget').text(gadget + " - " + price);
            jQuery('#promo').html(promo);
            jQuery('#commitmentBox').text(commitmentBox);
            if(mobtel=="0"){jQuery('#mobtel').text("none");} else {jQuery('#mobtel').text(mobtel);}
            jQuery('#name').text(username);
            jQuery('#email').text(eadd);
            jQuery('#dob').text(bday);
            jQuery('#add').text(address);
            jQuery("#pname, #pemail, #pdob, #padd").show();
          }
      }
    /*
    if(current_pos=="6") {
    
      jQuery('.marg20Left').css("position","absolute");
        jQuery('.marg20Left').css("margin-top","0px");
      jQuery('.deviceInfosIns').css("margin-top","-70px","important");
      jQuery('.deviceInfosIns').css("margin-left","9px","important");
      jQuery('.gallery-filter').css("width","210px");
      jQuery('.deviceInfosIns').css("width","210px");
      jQuery(".deviceInfos").addClass("hidden");
      jQuery(".deviceInfosIns").addClass("block2");

      var mode = getCookie("mode");
      var gadget = getCookie("gadget");
      var price = getCookie("price");
      var promo = getCookieR("promo");
      var commitmentBox = getCookieR("commitmentBox");
      var mobtel = getCookieR("mobtel");
      var username = getCookieR("username");
      var eadd = getCookieR("eadd");
      var bday = getCookieR("bday");
      var address = getCookieR("address");
      var globestore = getCookieR("globestore");
      
          if(mode!="edit"){      
      jQuery(".pnone").hide();
      jQuery('#globestore').text("None");
      jQuery('#gadget').text(gadget + " - " + price);
      jQuery('#promo').html(promo);
      jQuery('#commitmentBox').text(commitmentBox);
      jQuery('#mobtel').text(mobtel);
      jQuery('#name').text(username);
      jQuery('#email').text(eadd);
      jQuery('#dob').text(bday);
      jQuery('#add').text(address);
      jQuery('#globestore').text(globestore);
      jQuery("#pname, #pemail, #pdob, #padd").show();
      }
      } */
  } else {
    //alert(current_pos + "FALSE");
    jQuery("div.wizard a:nth-of-type(1)").attr("class","current");
    jQuery("div.wizard a:nth-of-type(1), div.wizard a:nth-of-type(2), div.wizard a:nth-of-type(3), div.wizard a:nth-of-type(4), div.wizard a:nth-of-type(5)").removeAttr("href");
  } 
  window.brand = $(".brand .select2-chosen").text();   
  window.allproducts = []; //wierd nito unneccessary 
  $("ul#products-list li.item").each(function(){     
    // window.allproducts.push($(this).find("h3.product-name").text());
     window.allproducts.push($(this));
  });

  jQuery("li.item").addClass("_display");
  /*  filter price adding marker to  prices */  

  $("ul#price li a").eq(0).find("span.price").eq(0).addClass("range0");
  $("ul#price li a").eq(1).find("span.price").eq(0).addClass("range1");
  $("ul#price li a").eq(2).find("span.price").eq(0).addClass("range2");
  $("ul#price li a").eq(3).find("span.price").eq(0).addClass("range3");
  $("ul#price li a").eq(4).find("span.price").eq(0).addClass("range4");
  $("ul#price li a").eq(5).find("span.price").eq(0).addClass("range5");
  /* filter price */
  
  if( $("div#phoneGallery").is(":visible") ){
    displayDefaultDevices();
  }
  
  /* Load More */
  $("a#loadmoreitems").click(function(){
    updatePageIndicator();  
    //lastPostFunc(); 
    var x = $("p.page-indicator").text();
   
    if($("._display[style='display: none;']").length == 0 ){
        $("a#loadmoreitems").hide();
    }
    if( $("._display[style='display: none;']").length == 0  || $("._display[style='display: block;']").length  == $("._display").length || $("._display[style='display: block;']").length  == x.replace("items", "").replace(/\s/g, "")){
          $("a#loadmoreitems").hide();   $("a#loadmoreitems").attr("style","display:none");
    }  

  });
  /* Load More */

  /* Order devices events  */
  /* mod by ian for reset 101114 */
  $("ul#price li dl dd a  , ul#price li a , .select2-results li").click(function(e){       
    e.preventDefault(); // prevent a tags
   // console.log(this);
   
    if(jQuery(this).text()!="All") {
      showReset(jQuery(this), "price");
      jQuery("#label-price, #price").hide(); // hide filter price
    }
    orderDevices(e,$(this));      
    updatePageIndicator(); 
    sortGallery(); 
  });

  $(".sort-by li").click(function(e){
    e.preventDefault(); // prevent a tags
    orderDevices(e,$(this));      
    updatePageIndicator(); 
    sortGallery();//alert("clicked sortby ");
  });
  
  $("select.brandsorter").change(function(e){     
    selectedBrand = jQuery("option:selected", this);
    orderDevices(e,$(this)); 
    updatePageIndicator();  
    jQuery("option", this).removeAttr('disabled');
    jQuery("option:selected", this).attr('disabled','disabled');
    //selectedBrand = jQuery(".brand .select2-chosen");
    //console.log("selectedBrand: " + selectedBrand.text());
    if(selectedBrand.text()!="All") {
      showReset(selectedBrand, "brand");
    } else {
      jQuery("#current-filter-brand-container").hide();
      hideReset();
    }
    //orderDevices(e,$(this),price); 
      
  });
    
  $(".sort-by ul li a").click(function(){
   
    $(".sort-by ul.tabs").find("li.active").removeClass("active");
    $(this).parent().addClass("active");
  });

    $(".orderby select").change(function(e){     
     orderDevices(e,$(this),price); 
  });  
  
  /* End Order devices events  */ 

  /* From gallery.php : brands dropdown */  
  jQuery("#brand-newcontainer").html(jQuery("#brand-container").html());

  var tabs = jQuery('#brand-newcontainer .tabs');

  jQuery('a', tabs).on( "click", function(e){
    e.preventDefault();
    jQuery(this).parent().addClass('active').siblings().removeClass('active');
  });

  jQuery('#brand-newcontainer .sorter a.tabs').on( "click", function(e) {
      e.preventDefault();
      var dataList = jQuery(jQuery(this).attr('href').toString());
      jQuery('#brand-newcontainer .sorter .data-list').filter('.active').hide().removeClass('active');
      dataList.show().addClass('active');
  });

  jQuery('#brand-newcontainer .data-list a').on( "click", function(e) {
    var ths = jQuery(this),pos = $this.parent().position().top;
    //$this.parents('.data-list').css('top', -pos).hide().removeClass('active');
    //$this.parents('.sorter').find('a.tabs').contents()[0].nodeValue = $this.text();   
  
    $(ths).parents('.data-list').css('top', -pos).hide().removeClass('active');
    $(ths).parents('.sorter').find('a.tabs').contents()[0].nodeValue = $(ths).text();   
  

  });  

  $('#btn_top').on("click",function(){
    scrollFrameHeight('0');
  });
  
  updatePageIndicator();  
  
  /* From gallery.php : brands dropdown */
  if(/gallery/.test(self.location.href)){ 
   var mode = getCookie("mode");
   if(mode=="edit"){
     jQuery('.deviceInfos').hide();
     jQuery('.deviceInfosIns').show();

     /*
       var gadget = getCookie("gadget") + " - P" + getCookie("price");
       var promo = getCookieR("promo");
       var commitment = getCookieR("commitmentBox");
       var prepaid = getCookie("mobtel");
    */
   
   jQuery('.marg20Left').css("position","absolute");
   jQuery('.marg20Left').css("margin-top","0px");
   jQuery('.deviceInfosIns').css("margin-top","-70px","important");
   jQuery('.deviceInfosIns').css("margin-left","9px","important");
   jQuery('.gallery-filter').css("width","210px");
   jQuery('.deviceInfosIns').css("width","210px");
   
   
   /*
     jQuery('.deviceBox').addClass("active");
     jQuery('.promoBox').addClass("active");
     jQuery('.commitmentBox').addClass("active");
     jQuery('.prepaidBox').addClass("active");
     jQuery('.profileBox').addClass("active");
     jQuery('.storeBox').addClass("active");   
   
     jQuery('#galgadget').html(gadget);
     jQuery('#galpromo').html(promo);
     jQuery('#galregper').html(commitment);
     jQuery('#galprepaid').html(prepaid);  

   */
   
  }else{
     jQuery('.deviceInfos').show();
     jQuery('.deviceInfosIns').hide();
  }
 }

  filterDeviceNumbers();
  $("div.brand .select2-container").click(function(){
       //alert(" dropdown ");
  });

  // . . . CROSS BROWSER FIXES  S A F A R I  S A F A R I  S A F A R I  . . . . . . 

  if( navigator.userAgent.search("Safari") >= 0 ){  //fix to display the load more
        updatePageIndicator();
        var x = $("p.page-indicator").text(); x.replace("items", "");
         // hide loadmore buttons 
        if($("._display[style='display: none;']").length == 0 || $("._display[style='display: block;']").length  == x.replace(/\s/g, "") ){
           $("a#loadmoreitems").hide(); 
        }
        if($("._display[style='display: none;']").length > 0 || $("._display[style~='display: none;']").length > 0 ){
                   $("a#loadmoreitems").show(); 
        }
        //SAFARI Loadmore items
          $("a#loadmoreitems").click(function(){
            updatePageIndicator();  
            lastPostFunc(); 
                       
            if($("._display[style='display: none;']").length == 0 ){
                  $("a#loadmoreitems").hide();
            }
            if( $("._display[style='display: none;']").length == 0  || $("._display[style='display: block;']").length  == $("._display").length || $("._display[style='display: block;']").length  == x.replace("items", "").replace(/\s/g, "")){
                    $("a#loadmoreitems").hide();  
            }  
            if($("._display[style='display: none;']").length > 0 || $("._display[style~='display: none;']").length > 0 ){
                   $("a#loadmoreitems").show();  $("a#loadmoreitems").attr("style","display:block;");
            }
         });  
  }
  // . . .CROSS BROWSER FIXES  S A F A R I  S A F A R I  S A F A R I  . . . . . . 

 // SAT log # 60
// markSelectedDevice();

}); // end of jquery document ready   . . . . end of jquery document ready . . . . .  end of jquery document ready

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) 
    {
      var c = ca[i].replace(/\s/g, "");
      if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}  

   
function getCookieR(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++){
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
  
function updatePageIndicator(){
   var string_item = " item";
   if($("._display").length > 1){
    string_item = " items";

   } 
   var s = $("._display").length  + string_item ; 


   $("p.page-indicator").text(s);
   //page-indicator
    
    if( $("._display").length  > 5 ){
        $("a#loadmoreitems").show(); 
    } 

    // hide loadmore buttons 
   
    filterDeviceNumbers();var x = $("p.page-indicator").text(); x = x.replace("items", "");
    //if($("._display[style='display: none;']").length == 0  || $("._display[style='display:block;']").length  == $("._display").length  ||  $("._display").length  == 0 ||  $("._display").length  < 9 ||  $("._display").length  == x.replace("items", "").trim() || $("._display[style='display: block;']").length  == $("._display").length ){
    if( $("._display[style='display: block;']").length  == x.replace(/\s/g, "") || $("._display[style='display: block;']").length  == $("._display").length || $("._display[style='display: none;']").length  == 0 ){       
            $("a#loadmoreitems").removeAttr("style");  $("a#loadmoreitems").attr("style","display: none;");  
            $("a#loadmoreitems").hide();         
    } // 
   
   //this is fix for safari
 
  
    if( navigator.userAgent.search("Safari") >= 0  ){ 
        if( $("._display").length  > 5 ){
            $("a#loadmoreitems").show(); 
            $("a#loadmoreitems").removeAttr("style");          
            $("a#loadmoreitems").show();  $("a#loadmoreitems").attr("style","display:block;");  
        }
        if($("._display[style='display: none;']").length  == 0 ){
             $("a#loadmoreitems").hide(); $("a#loadmoreitems").attr("style","display: none;"); //inline style works for safari 
        }

    }

}
function displayDefaultDevices() 
{ 
    $("li.item._display").each(function(index, value){ 
        if( index > 9){
           jQuery(this).hide();
        }
    });
    updatePageIndicator();  
}
function orderDevices(event, ths) 
{  
  //alert("!updated!");
  //reset bkup for reset
  var itemIn=0,bkup =" ";$("ul#products-list li").removeAttr("style"); 
  //reset
  $("ul#products-list li.item").removeClass("_hide");
  $("ul#products-list li.item").removeClass("_display");$("ul#products-list li.item").removeClass("_hide");  
  bkup = $( "ul#products-list").html();
  var  price="0", displayed=0,sortby = $(".sort-by li.active a").text() , orderby=$(".orderby .select2-chosen").text() , brand = $(".brand .select2-chosen").text();   
  //get price 
  if(ths.children().hasClass("price")){    
    
      /* . . this will add underline to the price list at left . . */   
      $("ul#price li a.filter").removeAttr("style");
      ths.attr("style","text-decoration: underline");
      $("ul#price li a.filter").removeClass("filter");
      ths.addClass("filter");      
      price = $("ul#price li a.filter span.price").eq(0).attr("class");  
     // price = price.replace(/\s/g, "") ;    
   
  }
  else{       
      price = $("ul#price li a.filter span.price").eq(0).attr("class");  //alert("p" + price);
  } 
  //console.log("Current price: " + price + " --- brand" + brand);
  if(price == "0" || price == null){ /*. .  When no price is underlined brand is selected . .*/
    $("ul#products-list li.item").each(function(){
      $(this).removeAttr("style");       
      if( brand == "All" || $(this).find("span.brand").text() == brand ){ 
         $(this).removeAttr("style");               
         $(this).addClass("_display"); 
         $(this).attr("style","display:block;");
         itemIn++;
      }else{
         //console.log("hide this ");console.log($(this).find("span.brand").text());
         $(this).addClass("_hide"); 
         $(this).hide(); 
      }
    });
  }else{
   // alert("has price");
    $( "ul#products-list li.item" ).each(function(){
     
      $(this).removeAttr("style");   
      
      if( $(this).find("span.brand").text() == brand || brand == "All"){    
       // console.log();  
        switch(price) {
          case "price range1": 
          /* . . . This will take the price string and parse to Float . . . */
          var p = $(this).find("span.price").text(); var str = p.replace(/Php/, " "); str = p.replace(/P/, " ");
          pr = parseFloat(str.replace(/\s/g, "") );
         /* . . . This will take the price and parse to Float . . . */
          if( pr  <= 2000.00){
            $(this).addClass("_display"); 
             itemIn++;
          } 
          else{
            $(this).addClass("_hide");             
          }                  
        break;
        case "price range2": 
          var p = $(this).find("span.price").text(); var str = p.replace(/Php/, " "); str = p.replace(/P/, " ");
          pr = parseFloat(str.replace(/\s/g, "") );
      
          if( pr  <= 3000.00 && pr >= 2001.00){
            $(this).addClass("_display"); itemIn++;            
          } 
          else{
            $(this).addClass("_hide");             
          }                  
        break;
        case "price range3": 
          var p = $(this).find("span.price").text(); var str = p.replace(/Php/, " "); str = p.replace(/P/, " ");
          pr = parseFloat(str.replace(/\s/g, "") );
      
          if( pr  <= 4000.00 && pr >= 3001.00){
            $(this).addClass("_display"); itemIn++;            
          } 
          else{
            $(this).addClass("_hide");             
          }                  
        break;
        case "price range4": 
          var p = $(this).find("span.price").text(); var str = p.replace(/Php/, " "); str = p.replace(/P/, " ");
          pr = parseFloat(str.replace(/\s/g, "") );
      
          if( pr  <= 5000.00 && pr >= 4001.00){               
            $(this).addClass("_display");itemIn++;
          } 
          else{
            $(this).addClass("_hide");             
          }                  
        break;
        case "price range5": 
          var p = $(this).find("span.price").text(); var str = p.replace(/Php/, " "); str = p.replace(/P/, " ");
          pr = parseFloat(str.replace(/\s/g, "") );
      
          if( pr  <= 9000.00 && pr >= 5001.00){           
            $(this).addClass("_display");  itemIn++;   
          } 
          else{
            $(this).addClass("_hide");             
          }                  
    break;  
    //add by ian to add display to all    
    default:
      $(this).addClass("_display");
      break;
        } //switch price               
      }
      else{
        $(this).addClass("_hide");         
      }
      if(brand == "All"){        
        $(this).removeAttr("style"); // bkit ?
      }
          
    }); //each      
     // $("ul#products-list li.item._display:lt(9)").attr("style","display:block!important;");
      $("._hide").hide(); 
     
  }
   
   $("._hide").hide();   
   //$(".category-products ul.gallery-products").children().remove();
   $(".category-products ul.gallery-products").html(window.allproducts); // weird, how this werks 
   
 
   if( itemIn == 0  ){
      $(".category-products ul.gallery-products").html(window.allproducts); //wierd tlga gumagana pdin
      return true;
   }

   $(".category-products ul.gallery-products").html(window.allproducts);
   displayDefaultDevices() ;   
   sortGallery();
   updatePageIndicator();
} /* end orderdisplayfunctions */

  /* from magento shop js scroll behavior */  

  function addToCartBundle(formId) {
    document.getElementById(formId).submit();       
  }

  jQuery(window).scroll(function(){
      /* modified version shop scroll */
      if(jQuery(window).scrollTop() >= ((jQuery(document).height() - jQuery(window).height()) - 250)){
           jQuery(".ajaxloader").show();          
           jQuery(".ajaxloader").hide();
      }
  });
  function filterDeviceNumbers(){
         
      var p = $(this).find("span.price").text(); var str = p.replace(/Php/, " "); str = p.replace(/P/, " ");
      pr = parseFloat(str.replace(/\s/g, ""));
        
     

          var r0 = 0 , r1 = 0 , r2 = 0 , r3 = 0  ,r4 = 0;
          $("ul li.item").each(function(){
              var pr = parseFloat( $(this).find(".customer-ctrl span.price").text().replace(/\s/g, "") )  , br = $(this).find("span.brand").text() ;
               
              if( pr <= 2000.00 && ( br == $(".brand .select2-chosen").text() || $(".brand .select2-chosen").text() =="All" ) ){                    
                  r0++;
              }  
              if( pr <= 3000.00 && pr >= 2001.00 && ( br == $(".brand .select2-chosen").text() || $(".brand .select2-chosen").text() =="All" ) ){
                  r1++;            
              } 
              if( pr <= 4000.00 && pr >= 3001.00 && ( br == $(".brand .select2-chosen").text() || $(".brand .select2-chosen").text() =="All") ){
                  r2++;                
              }
              if( pr <= 5000.00 && pr >= 4001.00 && (br == $(".brand .select2-chosen").text()|| $(".brand .select2-chosen").text() =="All" ) ){               
                  r3++;                
              } 
              if( pr <= 9000.00 && pr >= 5001.00 && ( br == $(".brand .select2-chosen").text() || $(".brand .select2-chosen").text() =="All" ) ){           
                  r4++ ;
              } 

          });
          $(".filters ul#price li span.filterData").eq(0).text("("+r0+")");
          $(".filters ul#price li span.filterData").eq(1).text("("+r1+")");
          $(".filters ul#price li span.filterData").eq(2).text("("+r2+")");
          $(".filters ul#price li span.filterData").eq(3).text("("+r3+")");
          $(".filters ul#price li span.filterData").eq(4).text("("+r4+")");
 

  }

  function lastPostFunc(){ 
    
    jQuery(".category-products li:hidden:lt(9):not(._hide)").show();  //less than 10 so nine  
    jQuery(".category-products li._display:lt(9):not(._hide)").show();   
    var x = $("p.page-indicator").text(); x = x.replace("items", "");
     if( navigator.userAgent.search("Safari") >= 0  ){ 
      
        if($("._display[style='display: none;']").length  == 0 || $("._display[style='display: block;']").length  == x.replace(/\s/g, "")){
             $("a#loadmoreitems").hide(); $("a#loadmoreitems").attr("style","display:none;");

        }

    }


    // adjust height ng iframe
    resizeIframe();

  }
 
  function clickLastPostFunc(){
    jQuery("html, body").animate({ scrollTop: jQuery(document).height() }, "slow");
  }
 
 /* end from magento shop js scroll behavior */ 

 function sortGallery(){

   
       if( $(".sort-by ul li.active").text() == "Name" ){          
            if( $(".orderby span.select2-chosen").text() == "Ascending" ){
                      //alert($(".sort-by ul li.active").text() );
                      //get all name put array
                      var arrNames = [] ; 
                      $("ul li.item._display").each(function(){
                          arrNames.push( $(this).find(".product-name a").text().replace(/\s/g, "") );
                      });  
                      //console.log("@sorting functions");
                      
                      // sort arrNames  order by ascending 
                      arrNames.sort(); // sorted na 
                      var temp_items = [];
                      var neworder = []; 
                      // match order to 

                      $(arrNames).each(function( index , value ){ 
                        $("ul li.item").each(function(ik,vl){
                            if( $(vl).find(".product-name a").text().replace(/\s/g, "") == value ){
                                temp_items.push(this);
                            }
                            else if( $(vl).hasClass("_hide") ){
                                temp_items.push(this);
                            }
                        });
                      }); 
                      
                      // console.log(temp_items); 
                      $("ul.gallery-products").empty();   
                      $("ul.gallery-products").html(temp_items);          

            }else{
                /* . . . Order by Descending Sort by Name. . . . */
                   var arrNames = [] ; 
                      $("ul li.item._display").each(function(){
                          arrNames.push( $(this).find(".product-name a").text().replace(/\s/g, "") );
                      });                        
                      // sort arrNames  order by ascending 
                      arrNames.sort();  arrNames.reverse();// sorted na 
                      var temp_items = [];
                      // match order to 
                      $(arrNames).each(function( index , value ){ 
                        $("ul li.item").each(function(ik,vl){
                            if( $(vl).find(".product-name a").text().replace(/\s/g, "") == value ){
                                temp_items.push(this);
                            }
                            else if( $(vl).hasClass("_hide") ){
                                temp_items.push(this);
                            }
                        });
                      }); 
                    
                      $("ul.gallery-products").empty();   
                      $("ul.gallery-products").html(temp_items);  
            }


      } /*. . . Sort By Price . . . */
      else if( $(".sort-by ul li.active").text() == "Price"){
                 
           var arrPrice= [] ; 
           if( $(".orderby span.select2-chosen").text() == "Ascending" ){
              //sort descending             
                 $("ul li.item._display").each(function(){
                     arrPrice.push( $(this).find(".customer-ctrl span.price").text().replace(/\s/g, "") );
                 }); 
                    
                 arrPrice.sort(function(a, b){return a-b}); //descending
                     var temp_items = [];
                // match order to 
                $(arrPrice).each(function( index , value ){ 
                $("ul li.item").each(function(ik,vl){
                      if( $(vl).find(".customer-ctrl span.price").text().replace(/\s/g, "") == value ){
                          temp_items.push(this);
                          //console.log(this);
                      }
                      else if( $(vl).hasClass("_hide") ){
                          temp_items.push(this);
                      }
                   });
                }); 
             $("ul.gallery-products").empty();  
             $("ul.gallery-products").html(temp_items);                 

           }else{
             
                $("ul li.item._display").each(function(){
                     arrPrice.push( $(this).find(".customer-ctrl span.price").text().replace(/\s/g, "") );
                }); 
                arrPrice.sort(function(a, b){return b-a}); //ascending
                     var temp_items = [];
                // match order to 
                $(arrPrice).each(function( index , value ){ 
                $("ul li.item").each(function(ik,vl){
                      if( $(vl).find(".customer-ctrl span.price").text().replace(/\s/g, "") == value ){
                          temp_items.push(this);
                          //console.log(this);
                      }
                      else if( $(vl).hasClass("_hide") ){
                          temp_items.push(this);
                      }
                   });
                }); 
             $("ul.gallery-products").empty();  
             $("ul.gallery-products").html(temp_items);  
           }

          $("ul.gallery-products li._display :lt(9)").show();  
           
      }
      else if( $(".sort-by ul li.active").text() == "Position"){
         
          var arrPos= [] ; 
           if( $(".orderby span.select2-chosen").text() == "Ascending" ){
              //sort descending             
                 $("ul li.item._display").each(function(){
                     arrPos.push( $(this).find(".customer-ctrl span.position").text().replace(/\s/g, "") );
                 }); 
                    
                arrPos.sort(function(a, b){return a-b}); //descending
                           

           }else{
             
                $("ul li.item._display").each(function(){
                     arrPos.push( $(this).find(".customer-ctrl span.position").text().replace(/\s/g, ""));
                }); 
                arrPos.sort(function(a, b){return b-a}); //ascending
                
           }

            var temp_items = [];
                // match order to 
                $(arrPos).each(function( index , value ){ 
                $("ul li.item").each(function(ik,vl){
                      if( $(vl).find(".customer-ctrl span.position").text().replace(/\s/g,"") == value ){
                          temp_items.push(this);
                          //console.log(this);
                      }
                      else if( $(vl).hasClass("_hide") ){
                          temp_items.push(this);
                      }
                   
                  });
                }); 
            
            $("ul.gallery-products").html(temp_items);  
            //alert("1");
      }
   lastPostFunc(); 
   displayDefaultDevices();  
   updatePageIndicator();    
} // end Sorting function 

    
function addHeader(){
      var compare1 = getCookie("maitaicompare1");      
      if (compare1 != null ){         
          $(".page-sub.desktop").removeAttr("style");
          $(".page-sub.desktop").attr("style","display:block;");
          $(".page-sub.desktop").show(); //console.log(compare1);
      } 
      if(compare1 == null || compare1 == undefined || compare1 == " " || compare1.length == 0 ){
           $(".page-sub.desktop").hide(); //console.log("no comparison");
      }     
  
}


function fixDropdown(){
  //alert("fix dropdown");
  var hideOption  = $("span.select2-chosen").text(); //console.log(hideOption);
  // $(".brand select2-offscreen").

}

/* add by ian for reset 101114 */
function showReset(filterText, which) {
  //filterText = filterText.text().trim(); 
  filterText = filterText.text();
  filterText = filterText.replace(/\s/g,"");

  jQuery("#gallery-filter-current-collapse").removeClass("expand");
  if(filterText=="All") {
    jQuery("#current-filter-"+which+"-container").hide();
    hideReset();
  } else {
    if(which=="price") filterText = filterText.substr(0,filterText.indexOf("("));
    
    jQuery("#current-filter-"+which+"-text").text(filterText);
    jQuery("#current-filter-"+which+"-container").show();
  }
  jQuery("#label-current-filter, #currentfilter").show();
}

function hideReset() {
    if(jQuery(".current-filter-text-container:visible").length == 1) {
        jQuery("#label-current-filter, #currentfilter").hide();
        return true;
      }
}
function markSelectedDevice(){
  //SAT60  

   
   var gName = $(".deviceInfosIns #selectedDevice").text();
   $("li.item .f-fix h3 a[title='"+gName+"']").parent("li").addClass("highlightDevice");
}


(function (w ) {
    w.fn.wGalleries = function(options) {
        var s = w.extend({
            // These are the defaults.
            _gadgetId:"",
            
        }, options );
        if (s._gadgetId !== ""){
            console.log("Current item: "+s._gadgetId);
            w("#gadget_"+s._gadgetId).addClass("highlightDevice");
            // @TODO - Do I need to remove the hightlight? In what scenario?
        }else{
            console.log("Theres no gadget selected.");
        }
        
    };

    w(document).ready(function(){
        
        w("products-list").wGalleries(
            {"_gadgetId":getCookie("gadgetid")});
        console.log("wDocument Ready");
    });
}( jQuery ));